﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Stu_sys.Entity;
using Stu_sys.Models;
using Stu_sys.utils;
using System.Text.Json;

namespace Stu_sys.Controllers
{
    public class BedroomController : Controller
    {
        private readonly MysqlContext _context;
        public BedroomController(MysqlContext context)
        {
            _context = context;
        }
        public IActionResult BedRoomList()
        {
            return View();
        }

        [HttpGet]
        public IActionResult GetBedRoomList()
        {
            var attrStr = MyUtils.GetAttributeToJsonStr(typeof(BedRoomViewModel));
            var bedRoomlist = _context.Bedrooms.ToList();
            var bedRoomStr = JsonSerializer.Serialize(bedRoomlist);
            var data = new
            {
                attr = attrStr,
                row = bedRoomStr
            };
            return Json(data);

        }

        [HttpPost]
        public IActionResult AddBedRoom(BedRoom bedRoom)
        {
            if (IsExistBedRoomName(bedRoom))
            {
                return Json(-1);
            }
            if (bedRoom == null)
            {
                return Json(-1);
            }
            _context.Bedrooms.Add(bedRoom);
            var res = _context.SaveChanges();
            return Json(res);
        }


        /// <summary>
        /// 名称是否已存在
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        private bool IsExistBedRoomName(BedRoom bedRoom)
        {
            var cr = _context.Bedrooms.Where(o => o.BedRoomName == bedRoom.BedRoomName).ToList();
            if (cr.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
